package com.ymy.thinking.in.spring.bean.initialization;

import com.ymy.thinking.in.spring.bean.factory.DefaultPersonFactory;
import com.ymy.thinking.in.spring.bean.factory.PersonFactory;
import org.springframework.context.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * Bean 初始化示例
 *
 * @author Ringo
 * @date 2021/8/26 22:41
 */
// IoC 容器会扫描到这个类
@Configuration
public class BeanInitializationDemo {

    public static void main(String[] args) throws InterruptedException {
        // 创建 IoC 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 设置包扫描
        applicationContext.scan("com.ymy.thinking.in.spring.bean.initialization.**");
        // 启动 Spring 应用上下文
        applicationContext.refresh();

        TimeUnit.SECONDS.sleep(1);
        // 依赖查找
        PersonFactory personFactory = applicationContext.getBean(PersonFactory.class);
        System.out.println(personFactory);

        System.out.println("Application Context 准备关闭...");
        // 关闭 Spring 应用上下文
        applicationContext.close();
        System.out.println("Application Context 已经关闭...");
    }

    @Lazy
    @Bean(initMethod = "initPersonFactory", destroyMethod = "destroyPersonFactory")
    public PersonFactory personFactory() {
        return new DefaultPersonFactory();
    }
}
